// 首页 - 商品列表页面逻辑
Page({
  data: {
    currentTab: 'all',
    currentTabIndex: 0,
    products: [],
    banners: [],
    couponVisible: true,
    loading: false,
    noMore: false,
    showBackTop: false,
    pageNum: 1,
    pageSize: 20,
    keyword: '',
    userInfo: null,
    systemInfo: {}
  },

  onLoad() {
    this.getSystemInfo()
    this.loadHomeData()
    this.showCouponIfNewUser()
    this.getUserInfo()
  },

  onShow() {
    // 页面显示时刷新数据
    if (this.data.products.length === 0) {
      this.loadProducts()
    }
    // 获取用户最新信息
    this.getUserInfo()
  },

  // 获取系统信息
  getSystemInfo() {
    const systemInfo = wx.getSystemInfoSync()
    this.setData({
      systemInfo
    })
  },

  // 获取用户信息
  getUserInfo() {
    const app = getApp()
    const userInfo = app.globalData.userInfo
    this.setData({
      userInfo
    })
  },

  // 加载首页数据
  async loadHomeData() {
    wx.showLoading({
      title: '加载中...',
    })

    try {
      await Promise.all([
        this.loadBanners(),
        this.loadProducts()
      ])
    } catch (error) {
      console.error('加载首页数据失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 加载轮播图
  async loadBanners() {
    try {
      const db = wx.cloud.database()
      const bannerRes = await db.collection('banners')
        .where({
          status: 1,
          startTime: db.command.lte(new Date()),
          endTime: db.command.gte(new Date())
        })
        .orderBy('sort', 'asc')
        .limit(5)
        .get()

      const banners = bannerRes.data.map(item => ({
        id: item._id,
        image: item.image,
        url: item.url,
        title: item.title
      }))

      this.setData({
        banners
      })
    } catch (error) {
      console.log('加载轮播图失败，使用默认数据')
      // 使用默认轮播图数据
      const defaultBanners = [
        {
          id: '1',
          image: '/images/banner1.jpg',
          url: '../activity/new-user'
        },
        {
          id: '2',
          image: '/images/banner2.jpg',
          url: '../activity/hot-sale'
        },
        {
          id: '3',
          image: '/images/banner3.jpg',
          url: '../activity/invite'
        }
      ]
      this.setData({ banners: defaultBanners })
    }
  },

  // 加载商品列表
  async loadProducts(refresh = false) {
    if (this.data.loading) return

    this.setData({
      loading: true
    })

    try {
      const db = wx.cloud.database()
      const productCollection = db.collection('products')

      // 构建查询条件
      let where = {
        status: 1,
        stock: db.command.gt(0)
      }

      // 根据当前分类筛选
      if (this.data.currentTab !== 'all') {
        where.type = this.data.currentTab
      }

      // 搜索关键词
      if (this.data.keyword) {
        where.name = db.command.regExp(this.data.keyword)
      }

      const skip = refresh ? 0 : (this.data.pageNum - 1) * this.data.pageSize

      const productRes = await productCollection
        .where(where)
        .skip(skip)
        .limit(this.data.pageSize)
        .orderBy('sort', 'desc')
        .orderBy('createTime', 'desc')
        .get()

      let products = []

      for (let item of productRes.data) {
        // 获取商品参与情况
        const participation = await this.getProductParticipation(item._id, item.groupCount, item.type)

        const product = {
          id: item._id,
          title: item.name,
          mainImage: item.images[0] || '/images/product-default.jpg',
          groupType: item.type,
          originalPrice: item.originalPrice,
          groupPrice: item.groupPrice,
          discount: Math.round((item.groupPrice / item.originalPrice) * 100) / 10,
          targetCount: item.groupCount,
          currentCount: participation.currentCount,
          progressPercent: participation.progressPercent,
          countdown: this.calculateCountdown(item.endTime),
          promotionTag: item.tag || '',
          stock: item.stock
        }

        products.push(product)
      }

      let finalProducts = []
      if (refresh) {
        finalProducts = products
      } else {
        finalProducts = [...this.data.products, ...products]
      }

      this.setData({
        products: finalProducts,
        loading: false,
        noMore: products.length < this.data.pageSize
      })

    } catch (error) {
      console.error('加载商品失败:', error)
      this.setData({
        loading: false
      })

      // 使用模拟数据作为备选
      const mockProducts = this.generateMockProducts()
      let finalProducts = []

      if (refresh) {
        finalProducts = mockProducts
      } else {
        finalProducts = [...this.data.products, ...mockProducts]
      }

      this.setData({
        products: finalProducts,
        noMore: mockProducts.length < this.data.pageSize
      })
    }
  },

  // 获取商品参与情况
  async getProductParticipation(productId, targetCount, groupType) {
    try {
      const db = wx.cloud.database()

      // 查询进行中团购活动
      const result = await db.collection('orders')
        .where({
          productId: productId,
          status: db.command.in(['pending', 'paid']),
          groupType: groupType
        })
        .count()

      const currentCount = result.total || 0
      const progressPercent = Math.floor((currentCount / targetCount) * 100)

      return {
        currentCount,
        progressPercent
      }
    } catch (error) {
      console.log('获取商品参与情况失败，使用模拟数据')
      return {
        currentCount: Math.floor(Math.random() * targetCount),
        progressPercent: Math.floor(Math.random() * 100)
      }
    }
  },

  // 计算倒计时
  calculateCountdown(endTime) {
    const end = new Date(endTime)
    const now = new Date()
    const remaining = end - now

    if (remaining <= 0) {
      return '00:00'
    }

    const hours = Math.floor(remaining / (1000 * 60 * 60))
    const minutes = Math.floor((remaining % (1000 * 60 * 60)) / (1000 * 60))

    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`
  },

  // 生成模拟商品数据（备选方案）
  generateMockProducts() {
    const types = ['traditional', 'lottery']
    const productTypes = ['数码电器', '生活用品', '美食特产', '服装配饰', '美妆护肤']
    const products = []

    for (let i = 0; i < this.data.pageSize; i++) {
      const groupType = types[Math.floor(Math.random() * types.length)]
      const targetCount = groupType === 'lottery' ?
        Math.floor(Math.random() * 40) + 10 :
        Math.floor(Math.random() * 48) + 2

      const currentCount = Math.floor(Math.random() * targetCount)
      const progressPercent = Math.floor((currentCount / targetCount) * 100)

      const originalPrice = Math.floor(Math.random() * 500) + 50
      const groupPrice = Math.floor(originalPrice * (0.6 + Math.random() * 0.3))
      const discount = Math.round((groupPrice / originalPrice) * 10 * 10) / 10

      const hours = Math.floor(Math.random() * 48) + 24
      const minutes = Math.floor(Math.random() * 60)
      const countdown = `${hours}:${minutes.toString().padStart(2, '0')}`

      products.push({
        id: Date.now() + i,
        title: `${productTypes[Math.floor(Math.random() * productTypes.length)]}高品质团购商品${i + 1}号`,
        mainImage: `/images/product${(i % 5) + 1}.jpg`,
        groupType,
        originalPrice,
        groupPrice,
        discount,
        targetCount,
        currentCount,
        progressPercent,
        countdown,
        promotionTag: i < 3 ? '新品尝鲜' : (i < 6 ? '限时特惠' : ''),
        stock: Math.floor(Math.random() * 100) + 10
      })
    }

    return products
  },

  // 切换分类标签
  switchTab(e) {
    const type = e.currentTarget.dataset.type
    if (this.data.currentTab === type) return

    this.setData({
      currentTab: type,
      products: [],
      pageNum: 1
    })

    this.loadProducts(true)
  },

  // 搜索输入处理
  onSearchInput(e) {
    const keyword = e.detail.value.trim()
    this.setData({
      keyword
    })

    clearTimeout(this.searchTimer)
    this.searchTimer = setTimeout(() => {
      this.searchProducts(keyword)
    }, 500)
  },

  // 搜索商品
  async searchProducts(keyword) {
    if (!keyword) {
      this.loadProducts(true)
      return
    }

    wx.showLoading({ title: '搜索中...' })

    try {
      const db = wx.cloud.database()
      const productRes = await db.collection('products')
        .where(db.command.or([
          {
            name: db.command.regExp(keyword, 'i')
          },
          {
            description: db.command.regExp(keyword, 'i')
          }
        ]))
        .where({
          status: 1
        })
        .limit(50)
        .get()

      const products = productRes.data.map(item => ({
        id: item._id,
        title: item.name,
        mainImage: item.images[0] || '/images/product-default.jpg',
        groupType: item.type,
        originalPrice: item.originalPrice,
        groupPrice: item.groupPrice,
        discount: Math.round((item.groupPrice / item.originalPrice) * 100) / 10,
        targetCount: item.groupCount,
        currentCount: 0,
        progressPercent: 0,
        countdown: this.calculateCountdown(item.endTime),
        promotionTag: '',
        stock: item.stock
      }))

      this.setData({
        products
      })
    } catch (error) {
      console.log('搜索失败，使用模拟数据')
      const mockProducts = this.generateMockProducts().filter(p =>
        p.title.includes(keyword)
      )
      this.setData({ products: mockProducts })
    } finally {
      wx.hideLoading()
    }
  },

  // 轮播图点击
  onBannerTap(e) {
    const url = e.currentTarget.dataset.url
    if (url) {
      wx.navigateTo({ url })
    }
  },

  // 领取优惠券
  async getCoupon() {
    const app = getApp()
    if (!app.globalData.openid) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    wx.showLoading({ title: '领取中...' })

    try {
      const result = await wx.cloud.callFunction({
        name: 'quickstartFunctions',
        data: {
          type: 'grantCoupon',
          openid: app.globalData.openid,
          couponType: 'newUser'
        }
      })

      if (result.result.success) {
        this.setData({
          couponVisible: false
        })
        wx.showToast({
          title: '领取成功',
          icon: 'success'
        })
      } else {
        wx.showToast({
          title: result.result.message || '领取失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('领取优惠券失败:', error)
      wx.showToast({
        title: '领取失败',
        icon: 'error'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 判断是否需要显示优惠券
  async showCouponIfNewUser() {
    try {
      const app = getApp()
      if (!app.globalData.openid) {
        this.setData({ couponVisible: true })
        return
      }

      const db = wx.cloud.database()
      const couponRes = await db.collection('coupons')
        .where({
          userId: app.globalData.openid,
          type: 'newUser',
          used: false,
          expireTime: db.command.gt(new Date())
        })
        .count()

      this.setData({
        couponVisible: couponRes.total === 0
      })
    } catch (error) {
      // 默认显示
      this.setData({ couponVisible: true })
    }
  },

  // 跳转到商品详情
  goToDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/product/detail?id=${id}`
    })
  },

  // 参与团购
  joinGroup(e) {
    const id = e.currentTarget.dataset.id
    const product = this.data.products.find(p => p.id === id)

    if (!product) return

    // 检查是否登录
    const app = getApp()
    if (!app.globalData.openid) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    if (product.groupType === 'lottery') {
      // 抽奖团购
      const deposit = Math.floor(product.groupPrice * 0.25)
      wx.showModal({
        title: '参与抽奖团购',
        content: `支付定金¥${deposit}参与抽奖，中奖后补齐尾款`,
        confirmText: '支付定金',
        success: (res) => {
          if (res.confirm) {
            this.goToParticipate(product.id, 'lottery', deposit)
          }
        }
      })
    } else {
      // 普通团购
      this.goToParticipate(product.id, 'traditional', product.groupPrice)
    }
  },

  // 去参与团购
  goToParticipate(productId, groupType, amount) {
    wx.navigateTo({
      url: `/pages/payment/index?productId=${productId}&groupType=${groupType}&amount=${amount}`
    })
  },

  // 分享商品
  onShare(e) {
    const id = e.currentTarget.dataset.id
    const product = this.data.products.find(p => p.id === id)

    if (!product) return

    // 生成分享数据
    const shareData = {
      title: `我发现了一个超值的${product.groupType === 'lottery' ? '抽奖' : '团购'}：${product.title}`,
      path: `/pages/product/detail?id=${id}&shareFrom=home`,
      imageUrl: product.mainImage
    }

    // 调用微信分享
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })

    // 保存分享信息到全局，供onShareAppMessage使用
    getApp().globalData.shareData = shareData

    // 记录分享行为，用于奖励统计
    this.recordShare(product.id)
  },

  // 记录分享行为
  async recordShare(productId) {
    try {
      const app = getApp()
      const db = wx.cloud.database()

      await db.collection('shareRecords').add({
        data: {
          userId: app.globalData.openid,
          productId: productId,
          shareTime: new Date(),
          shareFrom: 'home'
        }
      })
    } catch (error) {
      console.log('记录分享行为失败:', error)
    }
  },

  // 加载更多
  loadMore() {
    if (this.data.noMore || this.data.loading) return

    this.setData({
      pageNum: this.data.pageNum + 1
    })

    this.loadProducts()
  },

  // 滚动事件
  onPageScroll(e) {
    const scrollTop = e.scrollTop
    const showBackTop = scrollTop > 300

    if (this.data.showBackTop !== showBackTop) {
      this.setData({
        showBackTop
      })
    }
  },

  // 返回顶部
  backToTop() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
  },

  // 切换底部导航
  switchTabBar(e) {
    const index = e.currentTarget.dataset.index
    if (index === 0) return // 当前就是首页

    const pages = [
      '/pages/home/home',
      '/pages/group/list',
      '/pages/order/list',
      '/pages/user/profile'
    ]

    wx.switchTab({
      url: pages[index]
    })
  },

  // 下拉刷新
  async onPullDownRefresh() {
    await this.loadProducts(true)
    wx.stopPullDownRefresh()
  },

  // 页面分享
  onShareAppMessage() {
    const app = getApp()
    return app.globalData.shareData || {
      title: '超值团购，优惠多多！',
      path: '/pages/home/home'
    }
  },

  onShareTimeline() {
    return {
      title: '超值团购，优惠多多！',
      path: '/pages/home/home'
    }
  }
})